//
//  JCPopView.swift
//  SinaWeibo_18
//
//  Created by mac on 15/10/11.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit

//设置代理 ,改变titlebtn的状态
protocol JCPopViewDelegate: NSObjectProtocol{
    //代理方法
    func popViewWillDismiss()
}

class JCPopView: UIButton {
    
    //定义一个小灰框
    var imageFrameView: UIImageView?
    
    //声明代理属性
    weak var popViewDelegate: JCPopViewDelegate?
    
    //自定义初始化 弹出视图
    init(customView: UIView) {
        super.init(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight))
        
        //添加监听
        addTarget(self, action: "didClickCoverBtn", forControlEvents: UIControlEvents.TouchUpInside)
        setupFrameView(customView)
        self.backgroundColor = UIColor(white: 0, alpha: 0.2)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupFrameView(customView: UIView){
        //添加一个小灰框
        let image = UIImage(named: "popover_background")
        let imageFrameView = UIImageView(image: image?.stretchableImageWithLeftCapWidth(Int(image!.size.width*0.5), topCapHeight: Int(image!.size.height*0.5)))
        //开启用户交互
        imageFrameView.userInteractionEnabled = true
        imageFrameView.size = CGSizeMake(customView.width+10, customView.height+22)
       self.addSubview(imageFrameView)
        self.imageFrameView = imageFrameView
        
        //设置灰框的size随弹出内容视图的大小改变
            customView.x = 5
            customView.y = 13
        imageFrameView.addSubview(customView)
        
    }
    //覆盖按钮视图的点击事件
    @objc private func didClickCoverBtn(){
        
        self.dismiss()
    }
    //显示当前覆盖按钮视图
    func show(titleButton: UIButton){
        
        //转换坐标系,设置小灰框的位置
        let rect = titleButton.superview?.convertRect(titleButton.frame, toView: nil)
        self.imageFrameView?.centerX = titleButton.centerX
        self.imageFrameView?.y = CGRectGetMaxY(rect!)
        
        
        //添加到window
        let window = UIApplication.sharedApplication().windows.last
        window?.addSubview(self)
    }
    func dismiss(){
        //代理 告诉外界 覆盖视图即将移除
        if let del = self.popViewDelegate{
            del.popViewWillDismiss()
        }
        
        //移除
        removeFromSuperview()
    }
}
